#!/usr/bin/python
# encoding=utf-8
'''
pip install PyMySQL

https://pymysql.readthedocs.io/en/latest/
'''
import time
import pymysql
import random

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='abcd4321',
                             db='my-all-in',
                             charset='utf8mb4',
                             autocommit=True)


def new_register(inviteCode, cursor):
    print(inviteCode, 'new register task')
    return cursor.execute('''
            insert into t_job_task(type, biz, status, done)
            values('TREEX_NEW_REGISTER', %s, 'NEW', 0)
        ''', ('{"inviteCode":"' + inviteCode + '"}'))

try:
    with connection.cursor() as cursor:
        while True:
            cursor.execute('''
                select count(1) from t_job_task where type = 'TREEX_NEW_REGISTER' and status in ('ING', 'NEW')
            ''')
            qty1 = cursor.fetchone()[0]
            print('qty1: ' + str(qty1))
            cursor.execute('''
                select count(1) from t_treex_account where idStatus is null
            ''')
            qty2 = cursor.fetchone()[0]
            print('qty2: ' + str(qty2))
            cursor.execute('''
                select count(1) from t_treex_account where insertTime > now() - interval 10 second
            ''')
            qty3 = cursor.fetchone()[0]
            print('qty3: ' + str(qty3))
            if qty1 <= 4 and qty2 <= 50 and qty3 == 0:
                cursor.execute('''
                    select 
                        inviteCode 
                    from t_treex_account 
                    where 
                        inviteCode = 846354
                    ''')
                inviteCode = cursor.fetchone()[0]
                new_register(inviteCode, cursor)
            connection.commit()
            time.sleep(1)
finally:
    connection.close()
